package cn.dglydrpy.study.webserver.core;

import java.io.File;
import java.io.IOException;
import java.net.Socket;

import cn.dglydrpy.study.webserver.exception.EmptyRequestException;
import cn.dglydrpy.study.webserver.http.HttpRequest;
import cn.dglydrpy.study.webserver.http.HttpResponse;
import cn.dglydrpy.study.webserver.servlet.HttpServlet;

/**
 * 客户端处理器,线程任务处理类,用于处理某个客户端的请求并予以响应
 */
public class ClientHandler implements Runnable{
	
	private Socket socket;

	public ClientHandler(Socket socket){
		this.socket = socket;
	}
	
	public void run() {
		try {
			/*
			 * 处理客户端请求
			 */
			System.out.println("===== 1.解析请求  =====");
			HttpRequest request = new HttpRequest(socket);
			HttpResponse response = new HttpResponse(socket);	
			
			System.out.println("===== 2.处理请求  =====");
			//2.1:根据request获取资源的抽象路径
			String path = request.getRequestURI();
			//2.2:根据请求路径判断是否为请求一个业务操作
			HttpServlet servlet = ServerContext.getServlet(path);
			if(servlet!=null) {
				servlet.service(request, response);
			}else{
				File file = new File(Constant.WEBAPPS_DIR+path);
				if(file.exists()){
					System.out.println("该资源已找到");
					//将客户端请求的文件设置到response中
					response.setEntity(file);				
				}else{
					System.out.println("该资源不存在!");
					//响应404错误
					//1设置响应的状态代码为404
					response.setStatusCode(404);
					//2设置错误页面
					response.setEntity(new File(Constant.WEBAPPS_DIR+"sys/404.html"));
				}
			}
			
			System.out.println("===== 3.给予响应  =====");
			response.flush();
			System.out.println("===== 处理完毕! =====");
		} catch (EmptyRequestException e){
			System.out.println("空请求...");
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			//处理完请求并响应客户端后与其断开连接
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}

